<template>
  <view>
    <l-background color="#ffffff" />
    <l-tab-bar v-if="options.ioType == 0" id="tabBar" :tabs="tabs" :active-inx.sync="activeInx" @change="changeActiveInx" />
    <view class="tui-skeleton">
      <template v-if="list.length > 0">
        <tui-list-cell v-for="(item,index) in list" :key="index" @click="selectDriver(item)">
          <view v-if="options.ioType == 1" class="flex-row justify-between align-center">
            <view v-if="item.userId===-1" class="flex-row align-center form-item">
              <text class="text-30 color-primary">{{ item.nickname }}</text>
            </view>

            <template v-else>
              <view class="flex-row flex-center">
                <l-avatar :avatar="item.avatar" />
                <view class="margin-left-20 flex-column">
                  <text class="text-30 color-t1">{{ item.nickname }}</text>
                  <text v-if="type==='vehicle'" class="text-24 color-t3 margin-top-20">{{ item.vehicleNumber || '暂无关联车辆' }}</text>
                </view>
              </view>
              <l-tag v-if="item.examineStatus || item.examineStatus==0" plain :type="tagType(item.examineStatus)" :text="tagText(item.examineStatus)" />
            </template>
          </view>
          <view v-else class="flex-row justify-between align-center">
            <view class="flex-row flex-center">
              <l-avatar :avatar="item.avatar" />
              <view class="margin-left-20 flex-column">
                <text class="text-30 color-t1">{{ item.nickname }}</text>
              </view>
            </view>
            <view v-if="item.canChoose === 0" class="flex-row align-center flex-wrap">
              <l-tag v-for="(val,i) in item.cannotLabels" :key="i" plain type="error" :text="val" style="margin-right: 10rpx" />
            </view>
          </view>
        </tui-list-cell>
        <tui-nomore background-color="#ffffff" />
      </template>
      <template v-else>
        <tui-skeleton v-if="showSkeleton" :preload-data="preloadData" />
        <l-no-data v-else text="暂无符合条件的司机" type="data" />
      </template>
    </view>

    <tui-modal :show.sync="showModal" title="提示" :content="msg" @click="modalClick" />
  </view>
</template>

<script>
import { mapGetters, mapMutations } from 'vuex'
import { loading } from '@/common/util'
import { orderGetDriver, bindJudgment, getDriverList, getPublishDriverList } from '@/common/api/driver'
import { bindDriver } from '@/common/api/car'
import { examineStatus } from '../index'
import { preloadData } from './index'
export default {
  name: 'Index',
  data() {
    return {
      // 公共部分
      preloadData,
      showSkeleton: true,
      list: [],
      showModal: false,
      msg: '',
      item: {},
      type: '',
      // 下单部分
      options: {},
      // 添加车辆部分
      driverId: '',
      vehicleId: '',
      current: 1,
      directBind: false,
      tabs: [
        { title: '可选司机' },
        { title: '不可选司机' }
      ],
      activeInx: 0,
      optionalNo: [],
      optional: []
    }
  },
  computed: {
    tagText() {
      return (status) => {
        for (let i = 0; i < examineStatus.length; i++) {
          const item = examineStatus[i]
          if (status == item.value) return item.label
        }
      }
    },
    tagType() {
      return (status) => {
        switch (status) {
          case 0 : return 'warning'
          case 1 : return 'primary'
          case 2 : return 'success'
          case 3 : return 'error'
        }
      }
    },
    ...mapGetters({
      userId: 'userId',
      userInfo: 'userInfo'
    })
  },
  onLoad(options) {
    this.type = options.type || ''
    this.directBind = !!options.directBind
    if (options.type === 'vehicle') {
      this.driverId = options.driverId
      this.vehicleId = options.id
    } else {
      this.options = options
    }
    this.getList()
  },
  onPullDownRefresh() {
    this.getList()
  },
  methods: {
    /* 公共部分*/
    // 获取列表
    getList() {
      if (this.options.ioType === '0') {
        this.getPublishDriverList()
      } else if (this.type === 'vehicle') {
        this.vehicleGetDriverList()
      } else {
        this.orderGetDriverList()
      }
    },
    // 选择司机
    selectDriver(item) {
      if (this.options.ioType === '0' && item.canChoose === 0) {
        return false
      }
      if (this.type === 'vehicle') {
        this.vehicleSelectDriver(item)
      } else {
        this.orderSelectDriver(item)
      }
    },
    changeActiveInx(e) {
      this.list = this.activeInx === 0 ? this.optional : this.optionalNo
    },
    // 弹窗点击
    modalClick(e) {
      this.showModal = false
      if (e.index) {
        if (this.type === 'vehicle') {
          this.vehicleChooseDriver(this.item)
        } else {
          this.orderChooseDriver()
        }
      }
    },

    /* 下单部分*/
    // 获取司机列表
    async orderGetDriverList() {
      Object.assign(this.options, {
        nextDate: this.options.endDate
      })
      const [err, res] = await orderGetDriver(this.options)
      this.showSkeleton = false
      uni.stopPullDownRefresh()
      if (!this.$http.errorCheck(err, res)) return false
      let list = res.data.data
      if (!list) list = []
      const arr = []

      if (this.options.chosen && this.options.chosen !== 'undefined') {
        const driverList = JSON.parse(this.options.chosen)
        list.forEach(item => {
          if (!driverList.includes(item.userId)) arr.push(item)
        })
      }

      this.list = arr.length ? arr : list
    },
    // 选择司机
    async orderSelectDriver(item) {
      this.item = item
      const send = {
        driverId: item.userId,
        vehicleId: this.options.vehicleId,
        type: 1
      }
      const [err, res] = await bindJudgment(send)
      if (!this.$http.errorCheck(err, res)) return false
      const msg = res.data.data
      if (!msg.status) {
        if (msg.popupType == 1) {
          this.toast(msg.message)
        } else {
          this.msg = msg.message
          this.showModal = true
        }
      } else {
        this.modalClick({ index: 1 })
      }
    },
    // 确认选择司机
    orderChooseDriver() {
      this.setChooseDriverInfo({
        driverId: this.item.userId,
        driverName: this.item.nickname
      })
      this.jump()
    },

    /* 添加车辆部分*/
    // 获取司机列表
    async vehicleGetDriverList() {
      const [err, res] = await getDriverList({
        autoCompanyId: this.userId,
        page: this.current,
        driverId: this.driverId
      })
      this.showSkeleton = true
      uni.stopPullDownRefresh()
      if (!this.$http.errorCheck(err, res)) return false
      let list = res.data.data
      if (!list) list = []
      list.unshift({
        avatar: '',
        nickname: '无人',
        userId: -1,
        examineStatus: 1
      })
      this.list = list
    },
    async getPublishDriverList() {
      const [err, res] = await getPublishDriverList({
        companyId: this.userInfo.companyId,
        nextDate: this.options.endDate,
        startDate: this.options.startDate
      })
      this.showSkeleton = false
      uni.stopPullDownRefresh()
      if (!this.$http.errorCheck(err, res)) return false
      const list = res.data.data
      this.optional = []
      this.optionalNo = []
      list.forEach(item => {
        if (item.userId === this.options.driverId) {
          item.canChoose = 1
          this.optional.push(item)
        } else if (item.canChoose === 1) {
          this.optional.push(item)
        } else if (item.canChoose === 0) {
          this.optionalNo.push(item)
        }
      })
      this.list = this.activeInx === 0 ? this.optional : this.optionalNo
    },
    // 选择司机
    async vehicleSelectDriver(item) {
      if (item.userId === this.driverId) {
        this.jump()
        return
      }
      if (item.userId > 0) {
        this.getRelationDriverList(item.userId).then(res => {
          if (res.status) {
            this.vehicleChooseDriver(item)
          } else {
            if (res.popupType == 1) {
              this.toast(res.message)
            } else {
              this.showModal = true
              this.msg = res.message
              this.item = item
            }
          }
        })
      } else {
        this.vehicleChooseDriver(item)
      }
    },
    // 确认选择司机
    vehicleChooseDriver(item) {
      if (this.directBind) {
        this.bindLinkDriver(item.userId)
      } else {
        this.setChooseDriverInfo({
          driverIdSelect: item.userId,
          driverNameSelect: item.nickname,
          driverNameStatus: item.examineStatus
        })
        this.jump()
      }
    },
    // 获取司机关联车辆信息
    async getRelationDriverList(driverId) {
      const send = {
        driverId,
        type: 0
      }
      if (this.vehicleId) send.vehicleId = this.vehicleId
      const [err, res] = await bindJudgment(send)
      if (!this.$http.errorCheck(err, res)) {
        return false
      }
      return res.data.data
    },
    // 关联司机
    async bindLinkDriver(driverId) {
      const l = loading('加载中')
      if (driverId < 0) driverId = ''
      const [err, res] = await bindDriver({
        driverId,
        vehicleId: this.vehicleId
      })
      l.hide()
      if (!this.$http.errorCheck(err, res)) return false
      this.toast('关联司机成功', () => {
        this.jump()
      })
    },
    ...mapMutations({
      setChooseDriverInfo: 'order/setChooseDriverInfo'
    })

  }
}
</script>

<style scoped>
.optionalNo-div{
  border: 2rpx solid rgba(170, 170, 170, 1);
  padding: 0 10rpx;
  margin-right: 10rpx;
}
</style>
